package com.maychat.config;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

@Slf4j
@Configuration
public class RedisConfig<V> {

    @Value("${spring.data.redis.host}")
    private String redisHost;

    @Value("${spring.data.redis.port}")
    private Integer redisPort;

    @Value("${spring.data.redis.password}")
    private String password;

    @Bean(name = "redissonClient", destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        try {
            if (StringUtil.isNotBlank(password)) {
                Config config = new Config();
                String addr = "redis://" + redisHost + ":" + redisPort;
                config.useSingleServer().setAddress(addr).setPassword(password);
                log.info("redisson准备创建:{}", addr);
                return Redisson.create(config);
            } else {
                Config config = new Config();
                String addr = "redis://" + redisHost + ":" + redisPort;
                config.useSingleServer().setAddress(addr);
                log.info("redisson准备创建:{}", addr);
                return Redisson.create(config);
            }
        } catch (Exception e) {
            log.info("redisson启动失败！报错：:{}", e.getMessage());
            return null;
        }
    }


    @Bean
    public RedisTemplate<String, V> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, V> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // 设置value的
        template.setValueSerializer(RedisSerializer.json());
        // hash-key
        template.setHashKeySerializer(RedisSerializer.string());
        // hash-value
        template.setHashValueSerializer(RedisSerializer.json());
        template.afterPropertiesSet();
        return template;
    }
}
